<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>登录页面</title>
  <link rel="stylesheet" href="../lib/layui/css/layui.css">
  <link rel="stylesheet" href="../css/base.css">
  <link rel="stylesheet" href="../css/form.css">
</head>

<body>
  <div class="header container">登录页面</div>
  <form class="layui-form" lay-filter="loginForm">
    <span class="error">用户名或密码错误！</span>
    <label>
      用户名： <input type="text" name="username" lay-verify="required" placeholder="请输入用户名" autocomplete="off">
    </label>
    <label>
      密&nbsp;&nbsp;&nbsp;码： <input type="password" name="password" lay-verify="required" placeholder="请输入密码">
    </label>
    <p>还没账号，<a href="./register.html">去注册</a></p>
    <button lay-submit lay-filter="login">登录</button>
  </form>
  
  <script type="module">
    import '../lib/axios.js'
    import '../lib/layui/layui.js'
    layui.use(['form'], function () {
      var form = layui.form;
      var $ = layui.$;
      var layer = layui.layer;

      // 表单验证
      form.verify({
        required: function (value, item) {
          if (!value) {
            return '该项为必填项';
          }
        }
      });

      // 登录提交事件
      form.on('submit(login)', function (data) {
        var username = data.field.username;
        var password = data.field.password;

        axios.post('http://localhost:9000/users/login', {
          username: username,
          password: password
        })
          .then(function (response) {
            if (response.data.code===1) {
              layer.msg(response.data.message, {icon: 1});
              layui.data('shop',{
                key:'nickname',
                value:response.data.user.nickname
              })
              layui.data('shop',{
                key:'id',
                value:response.data.user.id
              })
              layui.data('shop',{
                key:'token',
                value:response.data.token
              })
              location.href='./index.html'
            } else {
              layer.msg(response.data.message, {icon: 0})
            }
          })
          .catch(function (error) {
            console.error('登录请求出错:', error);
            layer.msg('登录请求出错');
          });

        return false; // 阻止表单默认提交
      });
    });
  </script>
</body>

</html>